package com.edevp.common.mybatis.handler;

import com.edevp.common.core.dto.R;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

/**
 * @desc 统一异常处理
 * @author Blueeyedboy
 * @date 2022-07-05 5:22 PM
 **/
@ControllerAdvice
@Slf4j
public class SqlExceptionHandler {
	@ResponseBody
	@org.springframework.web.bind.annotation.ExceptionHandler(PersistenceException.class)
	public R mySQLSyntaxErrorException(PersistenceException ex) {
		return handerSqlException(ex);
	}

	@ResponseBody
	@org.springframework.web.bind.annotation.ExceptionHandler(MysqlDataTruncation.class)
	public R mysqlDataTruncation(SQLException ex) {

		log.error("SQLException:",ex);
		return R.error("系统修改数据异常");
	}

	@ResponseBody
	@org.springframework.web.bind.annotation.ExceptionHandler(SQLException.class)
	public R andleSQLException(SQLException ex) {

		log.error("SQLException:",ex);
		return R.error("系统修改数据异常");
	}

	@ResponseBody
	@org.springframework.web.bind.annotation.ExceptionHandler(DataIntegrityViolationException.class)
	public R andleSQLException(DataIntegrityViolationException ex) {

		log.error("DataIntegrityViolationException:",ex);

		return handerSqlException(ex);
	}

	private R handerSqlException(Exception ex){
		if(ex.getMessage() != null && ex.getMessage().indexOf("### Error updating database")>-1){
			//			System.out.println("=======111111==="+ex.getCause().getMessage());
			if(ex.getCause() != null && ex.getCause().getMessage() != null){
				if(ex.getCause().getMessage().endsWith("doesn't have a default value")){
					String field = ex.getCause().getMessage();
					field = field.substring(field.indexOf("Field")+5,field.indexOf("doesn"));
					return R.error("字段"+field+"不能为空");
				}else if(ex.getCause().getMessage().startsWith("Unknown column")){
					String field = ex.getCause().getMessage();
					field = field.substring(field.indexOf("column")+6,field.indexOf("in"));
					return R.error("数据库表不存在字段"+field+"");
				}
			}
		}

		log.error("SQLException:",ex);
		return R.error("系统修改数据异常");
	}
}
